package parallel

import (
	"fmt"
	"sync"
	"time"
)

type Job func(string) error

///共享协程池
type SPoolFunc struct {
	jobQueue    chan string
	wg          sync.WaitGroup
	workerNum   int
	TotalNum    int
	CounterOk   int
	CounterFail int
	CounterOut  int
	mutexFail   sync.Mutex
	mutexOk     sync.Mutex
	mutexOut    sync.Mutex
	TimeStart   int64
	TimeOut     int
	Debug       bool
	job         Job
}

// 协程池 timeout=0 关闭超时统计 debug=true 打开模式
func NewSPoolFunc(workerNum int, totalNum int, debug bool, job Job) *SPoolFunc {
	p := SPoolFunc{
		workerNum: workerNum,
		TotalNum:  totalNum,
		jobQueue:  make(chan string, workerNum),
		Debug:     debug,
		job:       job,
	}
	//任务开始时间记录
	p.TimeStart = time.Now().Unix()

	p.dispatch()
	return &p
}

func (p *SPoolFunc) dispatch() {
	p.wg.Add(p.workerNum)
	for i := 0; i < p.workerNum; i++ {
		//共享协程池
		go func() {
			//error process
			defer func() {
				p.wg.Done()
				if err := recover(); err != nil {
					fmt.Println("task run err", err)
				}
			}()

			for id := range p.jobQueue {
				if err := p.run(id); err != nil {
					panic(err)
				}
			}

		}()
	}
}

func (p *SPoolFunc) run(id string) error {
	//执行job
	return p.job(id)

}

// 提交任务
func (p *SPoolFunc) Commit(id string) {
	p.jobQueue <- id

}

// 等待组 关闭channel
func (p *SPoolFunc) Release() {
	close(p.jobQueue)
	p.wg.Wait()
}
